﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Net;
using System.Text;

namespace Dapper_Core.Common
{
    public class ImageUtility
    {
        /// <summary>
        /// 图片加底部文字并保存到本地
        /// </summary>
        /// <param name="path"></param>
        /// <param name="fileName"></param>
        /// <param name="text"></param>
        /// <param name="img"></param>
        /// <param name="paddingTop"></param>
        /// <param name="paddingLeft"></param>
        /// <param name="textColor"></param>
        /// <param name="textFont"></param>
        public static void AddWatermarkOnTheBottom(string path, string fileName, string text, string originalFileName,
            int paddingTop, int paddingLeft, Color textColor, Font textFont = null)
        {
            if (textFont == null)
            {
                textFont = new Font("宋体", 13, FontStyle.Bold);
            }
            //数据源来自File
            WebRequest myrequest = WebRequest.Create(originalFileName);//前台js传的path，可以是远程服务器上的，也可以是本地的
            WebResponse myresponse = myrequest.GetResponse();
            Stream imgstream = myresponse.GetResponseStream();
            System.Drawing.Image image = System.Drawing.Image.FromStream(imgstream);
            //把网络路径对应的图片保存到本地
            //MemoryStream ms = new MemoryStream();
            //image.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);

            //新图片的高与宽
            Bitmap bitmap = new Bitmap(image.Width, image.Height + 70);
            string backcolor = "#FFFFFF";
            Graphics g = Graphics.FromImage(bitmap);
            g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
            g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
            g.Clear(ColorTranslator.FromHtml(backcolor));
            g.DrawImage(image, new Point(0, 0));
            Brush b = new SolidBrush(textColor);
            string[] str = text.Split(';');
            for (int i = 0; i < str.Length; i++)
                g.DrawString(str[i], textFont, b, paddingLeft, image.Height + paddingTop + 33 * i);
            g.Dispose();
            //把修改后的图片保存到本地
            bitmap.Save(path + fileName, ImageFormat.Jpeg);
            bitmap.Dispose();

            #region Bitmap转byte[]
            //MemoryStream stream = new MemoryStream();
            //bitmap.Save(stream, ImageFormat.Jpeg);
            //byte[] data = new byte[stream.Length];
            //stream.Seek(0, SeekOrigin.Begin);
            //stream.Read(data, 0, Convert.ToInt32(stream.Length)); 
            #endregion
        }
    }
}
